package com.imy.virtual.helper.utils;

import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.util.Log;

import com.imy.virtual.client.core.VirtualCore;
import com.imy.virtual.client.ipc.VPackageManager;

import java.util.List;

public class LaunchIntentUtils {


  public static  Intent getLaunchIntent(String packageName, int userId) {
    VPackageManager pm = VPackageManager.get();
    Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
    intentToResolve.addCategory(Intent.CATEGORY_INFO);
    intentToResolve.setPackage(packageName);
    List<ResolveInfo> ris = pm.queryIntentActivities(intentToResolve, intentToResolve.resolveType(VirtualCore.get().getContext()), 0, userId);
    // Otherwise, try to find a main launcher activity.
    //重新找一次是多alis 的情况
    if (ris == null || ris.size() <= 0) {
      // reuse the intent instance
      intentToResolve.removeCategory(Intent.CATEGORY_INFO);
      intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
      intentToResolve.setPackage(packageName);
      ris = pm.queryIntentActivities(intentToResolve, intentToResolve.resolveType(VirtualCore.get().getContext()), 0, userId);
    }
    if (ris == null || ris.size() <= 0) {
      return null;
    }
    //查询到Intent
    Intent intent = new Intent(intentToResolve);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Log.i("getLaunchIntent"," ris.get(0).activityInfo.name:"+ ris.get(0).activityInfo.name);
    intent.setClassName(ris.get(0).activityInfo.packageName,
        ris.get(0).activityInfo.name);
    return intent;
  }


}
